document.addEventListener('DOMContentLoaded', () => {
    const display = document.querySelector('.display');
    const buttons = document.querySelectorAll('.button');

    let currentInput = '';
    let previousInput = '';
    let operation = null;

    buttons.forEach(button => {
        button.addEventListener('click', () => {
            const buttonText = button.textContent;

            if (buttonText >= '0' && buttonText <= '9') {
                handleNumber(buttonText);
            } else if (['+', '-', '*', '/'].includes(buttonText)) {
                handleOperator(buttonText);
            } else if (buttonText === 'C') {
                clearDisplay();
            } else if (buttonText === '=') {
                calculateResult();
            }
        });
    });

    function handleNumber(number) {
        if (previousInput !== '' && operation === null) {
            clearDisplay();
        }
        currentInput += number;
        display.value = currentInput;
    }

    function handleOperator(op) {
        if (currentInput === '') return;
        if (previousInput !== '') {
            calculateResult();
        }
        operation = op;
        previousInput = currentInput;
        currentInput = '';
    }

    function clearDisplay() {
        currentInput = '';
        previousInput = '';
        operation = null;
        display.value = '';
    }

    function calculateResult() {
        if (currentInput === '' || previousInput === '' || operation === null) return;
        let result;
        const prev = parseFloat(previousInput);
        const current = parseFloat(currentInput);

        switch (operation) {
            case '+':
                result = prev + current;
                break;
            case '-':
                result = prev - current;
                break;
            case '*':
                result = prev * current;
                break;
            case '/':
                result = prev / current;
                break;
            default:
                return;
        }

        currentInput = result.toString();
        operation = null;
        previousInput = '';
        display.value = currentInput;
    }
});